// pages/caseDescribe/caseDescribe.js
import request from '../../utils/config.js';
import util from '../../utils/util.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // isFile: false,
    windowHeight: wx.getSystemInfoSync().windowHeight - 91,
    caseInfoData: "",
    proDataList: "",
    lastLength: 0,
    firstLength: 0,
    isToastBg: false,
    isToast: false,
    wordDesShow: false,//文字描述
    serDes: "",//服务描述
    preventStatus: true,
    weatherEval: true,//是否评价过
    serviceAtt: [],
    responseAtt: [],
    specialtyAtt: [],
    serviceAttFlag: "",
    responseAttFlag: "",
    specialtyAttFlag: "",
    currentNum: 0,
    newFileList: new Array(),
    ifLJPJ: false,
    caseId: "",
    checkDiv: true,
    dimNum: 2,
    isFocus: false,
    inputValue: '',
    codes: ["", "", "", ""],
    nickName: "",
    validCodeCheck: false,
    showModel: true,
    animationM: {},
    animationS: {}
  },

  // 获取caseLi高度
  getRect: function () {
    let _this = this;
    wx.createSelectorQuery().select('#caseLiId').boundingClientRect(function (rect) {
      rect.id      // 节点的ID
      rect.height  // 节点的高度
      _this.showCaseLi(rect.height)
    }).exec()
  },
  showCaseLi: function (height) {
    console.log(height)
    // var animation = wx.createAnimation({
    //   duration: 200,
    //   timingFunction: "ease",
    //   delay: 0
    // })
    // this.animation = animation
    this.animation.height(height).step()

    // var animation2 = wx.createAnimation({
    //   duration: 200,
    //   timingFunction: "ease",
    //   delay: 0
    // })
    // this.animation2 = animation2
    this.animation2.height(0).step()

    this.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight - 177,
      animationM: this.animation.export(),
      animationS: this.animation2.export(),
    })
  },
  toTop: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.height(0).step()

    var animation2 = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation2 = animation2
    animation2.height(34).step()
    this.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight - 91,
      animationM: animation.export(),
      animationS: animation2.export()
    })
  },

  //swiper滑动
  changeCurrent: function (e) {
    if (e.detail.source == "touch") {
      this.setData({
        currentNum: e.detail.current
      })
    }
  },

  //点击案件进展
  tab1: function () {
    if (this.data.checkDiv) {
      return;
    }
    this.setData({
      currentNum: 0
    })
  },

  //点击附件列表
  tab2: function () {
    if (this.data.checkDiv) {
      return;
    }
    this.setData({
      currentNum: 1,
    })
  },

  /**
     * 点击输入框
     */
  openKeyboard: function () {
    this.setData({
      isFocus: true
    })
  },

  //获取监听手机号
  getPhoneNum: function (e) {
    console.log('输入手机号后四位===', e.detail.value)
    var text = e.detail.value;
    var textLength = text.length;
    var codeArray = new Array();
    for (var i = 0; i < (textLength > 4 ? 4 : textLength); i++) {
      var code = text.substr(i, 1);
      codeArray[i] = (code);
    }
    for (var i = codeArray.length; i < 4; i++) {
      codeArray.push("");
    }
    this.setData({
      codes: codeArray
    })
    if (textLength > 3) {
      var returnString = text.substr(0, 4);
      this.judgePhoneNum(returnString);
    }
  },

  //开始调接口验证
  judgePhoneNum: function (num) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId,
      mobileNo: num
    }
    let _this = this;
    request.requestLogin_api("invitedVerifyUser", headerInfo, bodyInfo, (obj) => {
      console.log("验证手机号成功==", obj)
      if (obj.data.isSuccess == 'T') {
        //保存案件Id
        // wx.setStorageSync("shareCaseId", _this.data.caseId);
        _this.setData({
          checkDiv: false,
          isFocus: false,
          dimNum: 0,
          validCodeCheck: false
        });
      } else {
        _this.setData({
          validCodeCheck: true
        });
      }
    }, (obj) => {
      console.log("验证手机号失败=", obj)
    })
  },

  //点击返回首页
  goHome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },


  // 展开合并 文件列表
  toggle: function (e) {
    let index = e.currentTarget.dataset.index;
    let fileLength = e.currentTarget.dataset.filelength
    let enforceStepList = this.data.newFileList;
    if (fileLength > 0) {
      if (enforceStepList[index].openFile) {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
      } else {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
        enforceStepList[index].openFile = true;
      }
      this.setData({
        newFileList: enforceStepList
      });
    }
  },


  //点击下载文件
  dowmloadFile: function (e) {
    let fileurl = e.currentTarget.dataset.url;
    let docName = e.currentTarget.dataset.name;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl)
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        console.log("读取文件失败=", res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("此处可以拿到转发的openid=", options.caseId)
    this.setData({
      caseId: options.caseId.split('|')[0],
      nickName: options.caseId.split('|')[1],
    });
  },

  //获取openid
  getOpenid: (_that) => {
    console.log("app.globalData.code:" + app.globalData.code);
    if (!app.globalData.userInfo) {
      wx.showLoading({
        title: '加载中',
      })
    }

    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      try {
        if (data.data.unionid) {
          app.globalData.unionid = data.data.unionid
        } else {
          //开始解析获取Unionid
          let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
          let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
          console.log('解密后 decodeData: ', decodeData);
          app.globalData.unionid = decodeData.unionid
        }
      } catch (e) {
        console.log("抛出异常=", e)
        wx.hideLoading()
        //开始解析获取Unionid
        let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
        let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
        console.log('解密后 decodeData: ', decodeData);
        app.globalData.unionid = decodeData.unionid
      }
      if (!app.globalData.sessionId) {
        _that.loginApi();
      } else {
        _that.queryCaseMessageList(_that);
      }
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //登录调用
  loginApi: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6'
    }
    let _this = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (obj) => {
      wx.hideLoading();
      if (obj.data.isSuccess == "F" && obj.data.errorCode == "ERROR_NOT_REG") {
        _this.getLoginInfo(_this);
        // wx.navigateTo({
        //   url: '../reg/reg',
        // })
      } else if (obj.data.isSuccess == "T") {
        console.log("用户登录成功=", obj)
        app.globalData.sessionId = obj.data.sessionId;
        //保存手机号
        app.globalData.mobileNo = JSON.parse(obj.data.body).mobileNo;
        app.globalData.userName = JSON.parse(obj.data.body).userName;
        // if (app.globalData.userName == _this.data.nickName) {
        //   this.setData({
        //     checkDiv: false,
        //     dimNum: 0
        //   });
        // }
        _this.queryCaseMessageList(_this);
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("用户登录失败=", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  // 获取登录信息
  getLoginInfo: (that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    let _this = that;
    console.log("bodyInfo====", bodyInfo)
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取用户信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        app.globalData.mobileNo = bodyData.memUserInfo.mobileNo;
        wx.hideShareMenu();
        _this.regErp(_this);
      } else {
        wx.navigateTo({
          url: '../reg/reg',
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取用户信息失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  // 用户注册
  regErp: function (that) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: app.globalData.mobileNo,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6',
      mobileCheckNo: "SUCCESS"
    }
    let _that = that;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      console.log("注册成功=", res)
      app.globalData.sessionId = res.data.sessionId;
      app.globalData.userName = JSON.parse(res.data.body).userName;
      _that.queryCaseMessageList();
    }, (res) => {
      console.log("注册失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //获取站内信消息列表
  queryCaseMessageList: function (that) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId
    }
    let _this = that;
    request.requestLogin_api("queryCaseMessage", headerInfo, bodyInfo, (obj) => {
      console.log("查询某个案件的站内信列表成功==", obj)
      // let messageList = JSON.parse(obj.data.body);
      var arr = JSON.parse(obj.data.body);
      arr.forEach(function (e) {
        e.date = e.messageTime.substring(4, 6) + "-" + e.messageTime.substring(6, 8);
        e.clock = e.messageTime.substring(8, 10) + ":" + e.messageTime.substring(10, 12)
      });

      _this.setData({
        proDataList: arr
      });
      wx.hideLoading();
      _this.getShareCaseInfo();
    }, (obj) => {
      wx.hideLoading();
      console.log("查询某个案件的站内信列表失败==", obj)
    })
  },

  //获取文件列表
  getFileList: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId
    }
    let _this = this;
    request.requestLogin_api("queryDocList4MP", headerInfo, bodyInfo, (obj) => {
      console.log("查询文件列表成功==", obj)
      let tempData = JSON.parse(obj.data.body);
      //开始处理数据
      let enforceTempList = tempData.lawsuitEnforceVo.enforceStepRecordWithBLOBs; //执行文本
      if (enforceTempList) {
        if (enforceTempList.length > 0) {
          enforceTempList.forEach(function (e, index) {
            let monthDate = util.timetrans(e.finishTime, "day");
            e.monthDate = monthDate.substring(5, 10)
            e.dayHM = util.timetrans(e.finishTime, "timeHM");
            e.openFile = false;
            if (index == 0) {
              e.stepFlag = true;
            } else {
              e.stepFlag = false;
            }
            if (e.enforceStepRecordDocs.length > 0) {
              let tempList = e.enforceStepRecordDocs;
              tempList.forEach(function (item) {
                let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
                item.docName = tempUrl.substring(10, tempUrl.length);
              });
              e.enforceStepRecordDocs = tempList;
            }
          });
        }
      } else {
        enforceTempList = new Array();
      }

      let lawsuitTempList = tempData.lawsuitEnforceVo.lawsuitStepRecordWithBLOBs; //诉讼文本
      if (lawsuitTempList) {
        if (lawsuitTempList.length > 0) {
          lawsuitTempList.forEach(function (e, index) {
            let monthDate = util.timetrans(e.finishTime, "day");
            e.monthDate = monthDate.substring(5, 10)
            e.dayHM = util.timetrans(e.finishTime, "timeHM");
            e.openFile = false;
            if (index == 0) {
              e.stepFlag = true;
            } else {
              e.stepFlag = false;
            }

            if (e.lawsuitStepRecordDocs.length > 0) {
              let tempList = e.lawsuitStepRecordDocs;
              tempList.forEach(function (item) {
                let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
                item.docName = tempUrl.substring(10, tempUrl.length);
              });
              e.lawsuitStepRecordDocs = tempList;
              e.enforceStepRecordDocs = tempList;
            } else {
              e.enforceStepRecordDocs = new Array();
            }
          });
        }
      } else {
        lawsuitTempList = new Array();
      }

      let docCaseDocs = tempData.docCaseDocs;//合同文本
      // console.log("合同文本=", docCaseDocs)
      let docTempCaseDocs = new Array();
      if (docCaseDocs.length > 0) {
        docCaseDocs.forEach(function (e, index) {
          e.monthDate = e.uploadDate.substring(4, 6) + "-" + e.uploadDate.substring(6, 8);
          e.dayHM = e.uploadTime.substring(0, 2) + "-" + e.uploadTime.substring(2, 4);
          e.openFile = false;
          let tempUrl = e.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
          e.docName = tempUrl.substring(10, tempUrl.length);
        });
        docTempCaseDocs = [{
          monthDate: docCaseDocs[0].monthDate,
          dayHM: docCaseDocs[0].dayHM,
          openFile: docCaseDocs[0].openFile,
          recordText: "合同文本",
          stepFlag: true,
          enforceStepRecordDocs: docCaseDocs
        }]
      }
      // console.log("合同文本=", docTempCaseDocs)

      let applyDocs = tempData.applyDocs;//申请资料
      let docTempApplyDocs = new Array();
      if (applyDocs.length > 0) {
        applyDocs.forEach(function (e) {
          e.monthDate = e.uploadDate.substring(4, 6) + "-" + e.uploadDate.substring(6, 8);
          e.dayHM = e.uploadTime.substring(0, 2) + "-" + e.uploadTime.substring(2, 4);
          e.openFile = false;
          let tempUrl = e.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
          e.docName = tempUrl.substring(10, tempUrl.length);
        });
        docTempApplyDocs = [{
          monthDate: applyDocs[0].monthDate,
          dayHM: applyDocs[0].dayHM,
          openFile: applyDocs[0].openFile,
          recordText: "申请资料",
          stepFlag: true,
          enforceStepRecordDocs: applyDocs
        }]
      }

      //合并数组
      let newArr = enforceTempList.concat(lawsuitTempList, docTempCaseDocs, docTempApplyDocs);
      _this.setData({
        newFileList: newArr
      });
    }, (obj) => {
      console.log("查询文件列表失败==", obj)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res) => {
        // 可以将 res 发送给后台解码出 unionId
        res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
        app.globalData.userInfo = res.userInfo;
        app.globalData.encryptedData = res.encryptedData;
        app.globalData.iv = res.iv;
        wx.showLoading({
          title: '加载中',
        })
        _that.getOpenid(_that);
      }, (res) => {
        console.log("获取用户信息失败=", res)
        _that.setData({
          showModel: true
        })
      });
    } else {
      if (!app.globalData.sessionId) {
        this.loginApi();
      } else {
        if (app.globalData.userName == this.data.nickName) {
          this.setData({
            checkDiv: false,
            dimNum: 0
          });
        }
        this.queryCaseMessageList(this);
      }
    }
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    that.getOpenid(that);
  },

  //验证手机号
  checkVerifyUserShare: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId
    }
    let _this = this;
    wx.hideLoading();
    request.requestLogin_api("checkVerifyUserShare", headerInfo, bodyInfo, (obj) => {
      console.log("验证是否需要输手机号成功==", obj)
      let flag = obj.data.body;
      if (app.globalData.userName == _this.data.nickName) {
        this.setData({
          checkDiv: false,
          dimNum: 0
        });
      } else {
        if (flag == 'SUCCESS' || flag == 'pass') {
          _this.setData({
            checkDiv: false,
            dimNum: 0
          });
        }
      }
    }, (obj) => {
      console.log("验证是否输入手机号失败=", obj)
    })
  },


  //获取案件详情接口
  getShareCaseInfo: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId
    }
    let _this = this;
    wx.hideLoading();
    request.requestLogin_api("queryCaseInfoDetail", headerInfo, bodyInfo, (obj) => {
      console.log("查询某个案件详情==", obj)
      let caseInfo = JSON.parse(obj.data.body);
      caseInfo.caseAmt = util.filterFormatAmt(caseInfo.caseAmt * 1 / 10000);
      caseInfo.status = util.investStatusFilter(caseInfo.status);
      _this.setData({
        caseInfoData: caseInfo
      });
      _this.checkVerifyUserShare();
    }, (obj) => {
      console.log("查询某个案件的详情失败=", obj)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})